package com.qf.service.impl;


import com.qf.mapper.ParentMapper;
import com.qf.pojo.Parent;

import com.qf.service.ParentService;
import com.qf.utils.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ParentServiceImpl implements ParentService {

    @Autowired
    ParentMapper parentMapper;

    @Override
    public ResultMsg selectAllParent(String name, Integer parentId, Integer parentStatus , Integer page, Integer limit) {
        page = page <= 1 ? 1 : page;
        name = name.equals("") ? null : name;
        parentId = parentId == -1 ? null : parentId;
        parentStatus = parentStatus == -1 ? null : parentStatus;
        List<Parent> parents = parentMapper.selectAllParent(name, parentId, parentStatus, (page - 1) * limit, limit);
        if (parents.size() == 0) return ResultMsg.FAILED(201, "no data was found");
        return ResultMsg.SUCCESS(0, parents, parentMapper.selectParentCount().getParentId());
    }

    @Override
    public ResultMsg selectOneParent(Integer parentId) {
        if (parentId == null) return ResultMsg.FAILED(202, "roleId can not be null");
        List<Parent> parents = parentMapper.selectParent(parentId);
        if (parents.size() != 1) return ResultMsg.FAILED(201, "no data was found");
        return ResultMsg.SUCCESS(parents.get(0));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMsg updateParent(Parent parent) {
        if (parentMapper.updateParent(parent) == 0)
            return ResultMsg.FAILED(201, "修改失败");
        return ResultMsg.SUCCESS();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMsg insertParent(Parent parent) {
        if(parent.getParentName()==null)
            return ResultMsg.FAILED(202, "参数不能为空");
        if (parentMapper.insertParent(parent) == 0)
            return ResultMsg.FAILED(201, "新增失败");
        return ResultMsg.SUCCESS(0, parent, 0);
    }

    @Override
    public ResultMsg updateParentStatus(List<Integer> parentIds, Integer parentStatus) {
        if (parentStatus != 0 && parentStatus != 1)
            return ResultMsg.FAILED(206, "The userStatus parameter does not allow this value");
        int i = parentMapper.updateParentStatus(parentIds, parentStatus);
        return new ResultMsg(0, i + " rows of data are successfully modified", null, 0);
    }

    @Override
    public ResultMsg deleteParent(List<Integer> parentIds) {
        int i = parentMapper.deleteParent(parentIds);
        if (i > 1)
            return new ResultMsg(0, i + " rows of data are deleted successfully", null, 0);
        else if (i==0)
            return new ResultMsg(201, i + " rows of data are deleted failed", null, 0);
        else
            return new ResultMsg(0, i + " row of data is deleted successfully", null, 0);   }
}
